//
//  LLNewFeatureViewController.swift
//  LLWeibo09
//
//  Created by 林 on 16/3/31.
//  Copyright © 2016年 lin. All rights reserved.
//

import UIKit

import SnapKit

private let reuseIdentifier = "Cell"

class LLNewFeatureViewController: UICollectionViewController {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 流水布局
    let layout = UICollectionViewFlowLayout()
    
    // 父类没有init()这个构造函数,子类不需要使用override
    init() {
        super.init(collectionViewLayout: layout)
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    
    /// collectionView设置
    private func prepareCollectionView() {
        // 设置layout参数
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        
        // 注册cell
         // UICollectionViewCell.self ==> [UICollectionViewCell class]
        collectionView?.registerClass(LLNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
   
}



// MARK: - collectionView数据源和代理方法
extension LLNewFeatureViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LLNewFeatuerPageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓存池里面攻取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LLNewFeatureCell
        
        // 设置cell要显示的页码
        cell.backgroundColor = UIColor.random()
        
        // 设置cell要显示的页码
        cell.index = indexPath.item
        
        // 不能在这里调用这个动画
        //        cell.startButtonAnimation()
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 计算当前页
        let page = Int(scrollView.contentOffset.x / UIScreen.mainScreen().bounds.width)
        
        // 判断当前是否是最后一页
        if page == LLNewFeatuerPageCount - 1 {
            
            // 创建indexPath 
            let indexPath = NSIndexPath(forItem: page, inSection: 0)
            
            // 获取indexPath对应的cell
            let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! LLNewFeatureCell
            
            // 让开始按钮动画
            cell.startButtonAnimation()
        }
    }
}

    // 自定义的cell
    class LLNewFeatureCell: UICollectionViewCell {
    // MARK: - 属性
        /// 当前显示的页数
        var index: Int = 0 {
            didSet {
                // 在控制器设置了页码之后,我们根据页码来显示对应的图片
                // 图片1, 2, 3, 4
                // index0 ,1 ,2 ,3
                bkgImageView.image = UIImage(named: "new_feature_\(index + 1)")
                
                // 只要cell要设置背景图片,就隐藏按钮
                startButton.hidden = true
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            prepareUI()
        }
        
        /// 开始按钮动画
        func startButtonAnimation() {
            startButton.hidden = false
            
            // 在开始动画之前,将transform Scale设置为0
            startButton.transform = CGAffineTransformMakeScale(0, 0)
            
            UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.startButton.transform = CGAffineTransformIdentity
                }, completion: nil)
        }
        
        // MARK: - 按钮点击事件
        func didClickStartButton() {
            // 切换到CZMainViewController
            AppDelegate.outSwitchRootViewController(LLMainViewController())
        }
        
        // 一般是设置frame.最好不要添加约束,约束会添加2次,当约束改变的时候会出现冲突
        override func layoutSubviews() {
            super.layoutSubviews()
        }
        
        private func prepareUI() {
            // 1.添加子控件,注意往contentView里面添加
            contentView.addSubview(bkgImageView)
            contentView.addSubview(startButton)
            
            // 2.添加约束
            bkgImageView.translatesAutoresizingMaskIntoConstraints = false
            startButton.translatesAutoresizingMaskIntoConstraints = false
            
            // 背景
            contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
            
            contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
            
            contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
            
            contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
            
            // 开始按钮
            contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
            contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        }

    

    // MARK: - 懒加载 
    /// 背景
    private lazy var bkgImageView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    
    private lazy var startButton: UIButton = {
       let button = UIButton()
        
        // 设置按钮
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "didClickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()


}

